﻿using Hx.ADSyncPlatform.Controllers.Base;
using Hx.ADSyncPlatform.Entity.Entities;
using Hx.ADSyncPlatform.Infrastructure.Expression.Common;
using Hx.ADSyncPlatform.Infrastructure.Page;
using Hx.ADSyncPlatform.Service;
using Hx.ADSyncPlatform.WebApi.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Hx.ADSyncPlatform.Controllers
{
    /// <summary>
    /// AzureAD
    /// </summary>
    [Route("api/plat/role")]
    //[Authorize(policy: "privilege")]
    [ApiController]
    public class Plat_SysRoleController : BaseController
    {
        private Plat_SysRoleService plat_SysRoleService;
        private Plat_SysPermissionService plat_SysPermissionService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="plat_SysRoleService"></param>
        /// <param name="plat_SysPermissionService"></param>
        /// <param name="serviceProvider"></param>
        public Plat_SysRoleController(Plat_SysRoleService plat_SysRoleService, Plat_SysPermissionService plat_SysPermissionService, IServiceProvider serviceProvider) : base(serviceProvider)
        {
            this.plat_SysRoleService = plat_SysRoleService;
            this.plat_SysPermissionService = plat_SysPermissionService;


        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="plat_SysRole"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<Result<Plat_SysRole>> Add([FromBody] Plat_SysRole plat_SysRole)
        {


            bool isRepeat = await plat_SysRoleService.Count(n => n.RoleName == plat_SysRole.RoleName) > 0;

            if (isRepeat) return await base.Fail<Plat_SysRole>($"角色名【{plat_SysRole.RoleName}】不允许重复!");

            plat_SysRole.RoleID = Guid.NewGuid();
            await plat_SysRoleService.Insert(plat_SysRole);
            await this.plat_SysPermissionService.SaveRolePermissions(plat_SysRole.RoleID, plat_SysRole.permissionIds);

            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】创建了系统角色【{plat_SysRole.RoleName}】 ");

            return await base.Success<Plat_SysRole>(plat_SysRole);

        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="plat_SysRole"></param>
        /// <returns></returns>
        [HttpPost("edit/{id}")]
        public async Task<Result<bool>> Edit([FromRoute] Guid id, [FromBody] Plat_SysRole plat_SysRole)
        {
            if (id == Guid.Empty) return await base.Fail<bool>($"未找到该角色!");

            bool isRepeat = await plat_SysRoleService.Count(n => n.RoleID != plat_SysRole.RoleID && n.RoleName == plat_SysRole.RoleName) > 0;

            if (isRepeat) return await base.Fail<bool>($"角色名【{plat_SysRole.RoleName}】不允许重复!");

            await plat_SysRoleService.Update(plat_SysRole);

            await this.plat_SysPermissionService.SaveRolePermissions(plat_SysRole.RoleID, plat_SysRole.permissionIds);

            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】修改了系统角色，角色id为【{id}】 ");

            return await base.Success<bool>(true);

        }


        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<Result<PageResult<Plat_SysRole>>> GetList([FromQuery] Pagination pagination,
            [FromQuery] Dictionary<string, string> param)
        {
            Expression<Func<Plat_SysRole, bool>> expression = n => true;

            if (param.ContainsKey("roleName"))
            {
                expression = expression.And(n => n.RoleName.Contains(param["roleName"]));
            }
            if (param.ContainsKey("isEnable"))
            {
                bool isEnable = false;
                if (bool.TryParse(param["isEnable"], out isEnable))
                {
                    expression = expression.And(n => n.IsEnable == isEnable);
                }

            }
            PageResult<Plat_SysRole> roles = await plat_SysRoleService.QueryPage(expression, pagination.pageNum, pagination.pageSize
                );

            return await base.Success<PageResult<Plat_SysRole>>(roles);

        }


        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet("all")]
        public async Task<Result<List<Plat_SysRole>>> GetAllRoles(int userId = 0)
        {
            Expression<Func<Plat_SysRole, bool>> expression = n => n.IsEnable == true;


            var roles = await plat_SysRoleService.Query(expression);
            if (userId > 0)
            {
                //判断当前用户是否为超级管理员
                if (false)
                {
                    roles = roles.Where(n => !n.IsSuperAdmin).ToList();
                }
            }

            return await base.Success<List<Plat_SysRole>>(roles);

        }


        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("delete/{id}")]
        public async Task<Result<bool>> Delete([FromRoute] Guid id)
        {
            bool deleted = await plat_SysRoleService.DeleteById(id);
            await this.plat_SysPermissionService.SaveRolePermissions(id, new List<Guid>());
            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】删除了系统角色，角色id为【{id}】 ");
            return await base.Success<bool>(true);
        }



    }
}
